<?php

namespace app\admin\controller\users;

use app\common\controller\Backend;
use think\Db;
use think\Env;
// 声明命名空间
use Obs\ObsClient;

/**
 * 大客户
 *
 * @icon fa fa-circle-o
 */
class Big extends Backend
{

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    private $redis;

    private $appid;
    private $secret;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Big;
        $this->appid = Env::get('wechat.appid');
        $this->secret = Env::get('wechat.secret');

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
    }

    /**
     * 查看
     */
    public function index()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with([
                    'bigs' => function ($query) {
                        $query->withField('id,name');
                    },
                ])
                ->where($where)
                //->where('admin_id', 'in', [0])
                ->order('id', $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }


                if (!empty($params['code'])){
                    $pan_arr = Db::table('fa_big')
                        ->where('code',$params['code'])
                        ->find();

                    if (empty($pan_arr)){
                        $this->error(__('绑定上级编号错误'));
                    }

                    $params['pid'] = $pan_arr['id'];
                }


                $params['code'] = 'co-looin'.get_strings(8,2);
                $params['url'] = $this->get_qrcode($params['code']);
                $params['binding_time'] = time();
                //var_dump($params);die();
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 获取分享码
     *
     */
    public function get_qrcode($did = 0){
        require '../vendor/obs/obs-autoloader.php';
        $pid = $did;
        //$str = '{"scene":"pid='.$pid.'"}';//测试
        //$str = '{"scene":"pid='.$pid.'","page":"pages/login/login"}';
        //$str = '{"scene":"'.$pid.'","page":"pages/login/login"}';
        //$str = urlencode('pid='.$pid);
        $str = '{"scene":"did*'.$pid.'","page":"pages/login/login"}';

        $appid = $this->appid;
        $secret = $this->secret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;

        $access_toke = $this->redis->Get('access_toke');//设置redis

        if ($access_toke == false){
            $result = file_get_contents($url);
            $result = json_decode($result,true);

            if (isset($result['errcode'])){
                $this->error('token获取失败',$result);
            }
            //将access_toke存redis
            $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
            $access_toke = $result['access_token'];
        }

        //header('Content-type: image/jpeg');
        $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

        $result = http($urls,$str,'POST',[],true);

        $results = json_decode($result,true);


        if (isset($results['errcode'])){
            if ($results['errcode'] == 40001){
                $result = file_get_contents($url);
                $result = json_decode($result,true);

                if (isset($result['errcode'])){
                    $this->error('token获取失败',$result);
                }
                //将access_toke存redis
                $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
                $access_toke = $result['access_token'];

                $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

                $result = http($urls,$str,'POST',[],true);
            }else{
                return $result;
            }

        }


        //var_dump($result);die();
        $name = time() . uniqid() . '.jpg'; //临时文件名称

        $dir_path = "./log/logs";
        if (!file_exists($dir_path)){
            mkdir($dir_path,755,1);
        }
        $path = $dir_path . '/' . $name;

        if (file_put_contents($path, $result)){
            //开始obs上传,引入文件
            // 创建ObsClient实例
            $obsClient = new ObsClient([
                'key' => 'W2O4GDBTRQIFRODHXVDU',
                'secret' => '8jpkOkdEFdgZh53DzZnCkIrHczPfIWc8RVK1p9iQ',
                'endpoint' => 'https://obs.cn-south-1.myhuaweicloud.com'
            ]);

            try {

                $resp = $obsClient->putObject([
                    'Bucket' => 'obs-c95m',
                    'Key' => 'luyin/'.$name,
                    //'SourceFile' => $f_path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                    'SourceFile' => $path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                ]);
                unlink($path); //上传本地临时文件

                $img_name =  'https://img.looin.cn/luyin/'.$name;

//                $ar = [
//                    'img_name' => $img_name,
//                ];

                return $img_name;


            } catch (\Obs\ObsException $obsException){
                $this->error($obsException->getExceptionCode(),$obsException->getExceptionMessage());
            }
        }
    }


}
